package com.boy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.boy.commonutils.handler.WhdException;
import com.boy.entity.*;
import com.boy.entity.dto.AccountDto;
import com.boy.entity.modle.AccountType;
import com.boy.mapper.*;
import com.boy.service.AccountService;
import com.boy.service.weiXin.WxService;
import com.boy.tool.enumClass.ExceptionCode;
import com.boy.tool.domain.Pos;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author whd
 * @since 2024-05-23
 */
@Service
@Slf4j
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements AccountService {

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private AccountMapper accountMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private CodeMapper codeMapper;

    @Autowired
    private LogMapper logMapper;

    @Autowired
    private WxService wxService;


    @Override
    public List<Permission> findPermission(String accountId) {
        Account account = accountMapper.selectById(accountId);
        if (account == null) throw new WhdException(ExceptionCode.HADLE_EXCEPTION, "不存在此用户");
        String[] roles = account.getRoles().split(",");
        List<Role> roleList = roleMapper.selectBatchIds(Arrays.asList(roles));
        ArrayList<String> ids = new ArrayList<>();
        roleList.forEach((it) -> {
            Collections.addAll(ids, it.getPermissionIds().split(","));
        });
        if (ids.isEmpty()) return new ArrayList<>();
        return permissionMapper.selectBatchIds(ids);
    }

    @Override
    public Account login(String phone, String password, String ip) {
        QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", phone).eq("password", password);
        Account account = accountMapper.selectOne(queryWrapper);
        if (account == null) throw new WhdException(ExceptionCode.HADLE_EXCEPTION, "不存在此用户");
        logMapper.insert(new Log("用户登录成功", account.getNick(), ip, "登录成功"));
        return account;
    }

    @Override
    public AccountDto me(String id) {
        Account account = accountMapper.selectById(id);
        AccountDto accountDto = new AccountDto(account);
        accountDto.setLikeNum(0L);
        return accountDto;
    }

    @Override
    public Account created(String phone, String name, String type, String roles, String email) {
        Account account = new Account();
        account.setPhone(phone);
        account.setMail(email);
        account.setPassword(phone.substring(phone.length() - 5));
        account.setNick(name);
        account.setRoles(roles);
        AccountType accountType = AccountType.valueOf(type);
        // if (accountType==null)throw new  WhdException(501,"传入字段不是枚举字段");
        account.setType(accountType);
        accountMapper.insert(account);
        return account;
    }

    @Override
    public IPage<Account> find(@RequestBody Pos pos, String name, String phone) {
        Page<Account> page = new Page<>(pos.getCurPage(), pos.getPageSize());
        QueryWrapper<Account> wrapper = new QueryWrapper<>();
        wrapper.like(name != null, "nick", name).like(phone != null, "phone", phone);
        return accountMapper.selectPage(page, wrapper);
    }

    @Override
    public Account emailLogin(String email, String code, String ip) {
        QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mail", email);
        Account account = accountMapper.selectOne(queryWrapper);
        Code c = codeMapper.selectByEmail(email);

        if (!code.equals(c.getCode()))
            throw new WhdException(ExceptionCode.SYSTEM_RUN_EXCEPTION, "不存在此验证码，或验证码过期");
        c.setUsed(1);
        if (account == null) {
            Random random = new Random();
            long min = 10000000000L; // 最小的 11 位数
            long max = 99999999999L; // 最大的 11 位数
            long randomNum = min + ((long) (random.nextDouble() * (max - min)));
            Account user = created(String.valueOf(randomNum), email.split("@")[0], AccountType.USER.name(), "", email);
            logMapper.insert(new Log("用户注册成功", account.getNick(), ip, "注册成功"));
            return user;
        }
        logMapper.insert(new Log("用户登录成功", account.getNick(), ip, "登录成功"));
        return account;

    }

    @Override
    public void send(String accountId) throws WxErrorException {
        Account account = accountMapper.selectById(accountId);
        wxService.sendMessage(account);
    }

    // @Scheduled(cron = "0 30 22 * * ?")
    @Scheduled(cron = "0 0 0 * * ?")
    @Override
    public void sendAll() throws WxErrorException {
        for (Account account : accountMapper.selectList(new QueryWrapper<Account>().eq("type", "USER"))) {
            log.info(account.getNick() + "用户上传信息");
            wxService.sendMessage(account);
        }
    }


}
